package com.vercon.commonmirror.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.NonNull;

import com.vercon.commonmirror.Constants;
import com.vercon.commonmirror.R;
import com.vercon.commonmirror.base.BaseActivity;
import com.vercon.commonmirror.update.InstallUtils;
import com.vercon.commonmirror.utils.LogUtils;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by csh on 2020/7/27
 * 权限申请
 */

public abstract class PermissionsActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    final int RC_CAMERA_PERM_LOCATION = 1013;
    private final String[] locationPerms = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
            Manifest.permission.SYSTEM_ALERT_WINDOW

    };
    private AlertDialog mDialog;

    /**
     * 在这个页面请求基本的动态权限， 比如定位， 存储等。
     */
    public void verifyPermissionForAPPBase() {
        LogUtils.e("PermissionsActivity", "verifyPermissionForAPPBase  在这个页面请求基本的动态权限， 比如定位， 存储等");

        if (EasyPermissions.hasPermissions(this, locationPerms)) {
            LogUtils.e("PermissionsActivity", "hasPermission");
            hasPermission();
        } else {
            LogUtils.e("PermissionsActivity", "程序需要定位权限");

            // 提示用户去应用设置界面手动开启权限
            if (Build.MODEL.equals(Constants.rk3368)) {
                //适配3368主板，采用正常获取权限操作，会导致闪退，所以只能让用户点击进入设置手动开启
                showDialogTipUserGoToAppSettting();
            } else {
                EasyPermissions.requestPermissions(this, getString(R.string.app_permission), RC_CAMERA_PERM_LOCATION, locationPerms);
            }
        }
        //检测是否允许安装应用
        InstallUtils.checkInstallPermission(this, new InstallUtils.InstallPermissionCallBack() {
            @Override
            public void onGranted() {
//                LogUtils.d(TAG, "允许安装应用");
            }

            @Override
            public void onDenied() {
                System.exit(0);
            }
        });

    }

    protected abstract void hasPermission();

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, list)) {
            //这个方法有个前提是，用户点击了“不再询问”后，才判断权限没有被获取到
            new AppSettingsDialog.Builder(this)
                    .setRationale(getString(R.string.no_permission))
                    .setTitle(getString(R.string.required_permissions))
                    .build()
                    .show();
            LogUtils.e("PermissionsActivity", "没有该权限，此应用程序可能无法正常工作。打开应用设置界面以修改应用权限");

        } else if (!EasyPermissions.hasPermissions(this, locationPerms)) {
            //这里响应的是除了AppSettingsDialog这个弹出框，剩下的两个弹出框被拒绝或者取消的效果
            LogUtils.e("PermissionsActivity", "这里响应的是除了AppSettingsDialog这个弹出框，剩下的两个弹出框被拒绝或者取消的效果");
            finish();
        }

    }

    /**
     * 提示用户去应用设置界面手动开启权限
     */
    private void showDialogTipUserGoToAppSettting() {

        mDialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.warm_prompt))
                .setMessage(getString(R.string.please_get_permission))
                .setPositiveButton(getString(R.string.to_setup), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
//                        dialog.dismiss();
                    }
                })
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    /**
     * 跳转到当前应用的设置界面
     */
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            if (!EasyPermissions.hasPermissions(this, locationPerms)) {
                // 这里响应的是AppSettingsDialog点击取消按钮的效果
                LogUtils.e("PermissionsActivity", "这里响应的是AppSettingsDialog点击取消按钮的效果");
                finish();
            }
        } else if (requestCode == 123) {
            //适配3368主板
            //权限管理
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                if (EasyPermissions.hasPermissions(this, locationPerms)) {
                    //权限获取成功
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                    hasPermission();
                } else {
                    // 权限没有授权
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                }

            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        LogUtils.e("PermissionsActivity", "PermissionsActivity-onRequestPermissionsResult " + permissions.length + "  " + requestCode + "  " + grantResults.length);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
